﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace WorkFlowCore.UserSelectors
{
    public class UserSelectorManager
    {
        private static object objLock = new object();
        private IServiceProvider serviceProvider;
        static UserSelectorManager()
        {
            AllUserSelectors = new List<UserSelector>();
        }

        public UserSelectorManager(IServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
        }



        public static List<UserSelector> AllUserSelectors { get; private set; }
        public static void RegisterSelector(string selectorId, string selectorName, Type selectorType, string description)
        {
            lock (objLock)
            {
                if (AllUserSelectors.Where(s => s.Id == selectorId).Any())
                    return;
                //throw new Exception($"相同的选择器id[{selectorId}]已存在");
            }

            AllUserSelectors.Add(new UserSelector(selectorId, selectorName, selectorType, description));
        }
        /// <summary>
        /// 从 程序集注册
        /// </summary>
        /// <param name="assemblies"></param>
        public static void RegisterSelector(params Assembly[] assemblies)
        {
            foreach (var assembly in assemblies)
            {
                var types = assembly.GetTypes().Where(t => t.GetCustomAttribute<UserSelectorAttribute>() != null);

                foreach (var type in types)
                {
                    var attr = type.GetCustomAttribute<UserSelectorAttribute>();
                    var selectorId = type.FullName;
                    var selectorName = attr.Name ?? type.FullName;
                    RegisterSelector(selectorId, selectorName, type, attr.Description);
                }
            }
        }


        /// <summary>
        /// 获取选择器
        /// </summary>
        /// <param name="selectorId"></param>
        /// <param name="selectorCreator"></param>
        /// <returns></returns>
        public virtual IUserSelector GetUserSelector(string selectorId)
        {
            var selector = AllUserSelectors.FirstOrDefault(s => s.Id == selectorId);
            if (selector == null) return null;
            try
            {
                return (IUserSelector)serviceProvider.GetService(selector.SelectorType);
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
